<?php

namespace Acme\CommonBundle\Form\DataTransformer;

use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\DataTransformerInterface;
use Doctrine\Common\Persistence\ObjectManager;

class UniversityToIdTransformer implements DataTransformerInterface
{
	private $om;

	public function __construct(ObjectManager $om)
	{
		$this->om = $om;
	}

	// transforms the Issue object to a string
	public function transform($val)
	{
		if (null === $val) {
			return '';
		}

		return $val->getId();
	}

	// transforms the issue number into an Issue object
	public function reverseTransform($val)
	{
		if (!$val) {
			return null;
		}

		$university = $this->om->getRepository('AcmeCommonBundle:ConstUniversity')->findOneById($val);

		if (null === $university) {
			throw new TransformationFailedException(sprintf('An university with number %s does not exist!', $val));
		}

		return $university;
	}
}